package ess.control;

import java.util.Timer;
import java.util.TimerTask;

import ess.hardware.DoorClosingSensor;
import ess.hardware.DoorClosingSensorEvent;

public class ElevatorStateOpened extends ElevatorState {

	boolean delayed;
	Timer timer;
	public ElevatorStateOpened(ElevatorProxy proxy) {
		super(proxy, STATE_OPENED);
		delayed = true;
	}

	public void processState() {
		//if(proxy.getPreviousState() == proxy.getState(STATE_STOPPED)){
		{
			delayed = false;
			timer = null;
			timer = new Timer();
			timer.schedule(new DelayedTimerTask(proxy, this), 2000);
		}
	}

	public void setDelayed(){
		delayed = true;
	}

	public ElevatorState handleCommand(Command c) {
		if(c.equals(Command.COMMAND_DOOR_CLOSE) && proxy.getObstacleDetected() == false)
		{
			return proxy.getState(STATE_CLOSING);
		}
		else if(c.equals(Command.COMMAND_DOOR_OPEN)){
			proxy.notifyDoorStateChanged(new DoorClosingSensorEvent(null, DoorClosingSensor.DOOR_OPENED));
		}
		return null;
	}

	class DelayedTimerTask extends TimerTask{
		ElevatorStateOpened state;
		ElevatorProxy proxy;
		public DelayedTimerTask(ElevatorProxy proxy, ElevatorStateOpened state){
			this.state = state;
			this.proxy = proxy;
		}

		public void run() {
			state.setDelayed();
			proxy.putCommand(Command.COMMAND_DOOR_CLOSE);
			
		}
		
	}

}
